import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import jwt_decode from 'jwt-decode'
import { reject } from 'lodash'

const state = {
  token: getToken(),
  usercontex: undefined,
  avatar: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_CONTEXT: (state, context) => {
    state.usercontex = context
  },
  SET_USER_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit, dispatch }, loginData) {
    return new Promise((resolve, reject) => {
      login(loginData).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        // set user info
        var decodedToken = jwt_decode(data.token)
        commit('SET_USER_CONTEXT', decodedToken)
        // set user roles
        var userRoles = []
        for (var i = 0; i < decodedToken.roles.length; i++) {
          var roleName = decodedToken.roles[i].RoleName
          userRoles.push(roleName)
        }
        commit('SET_USER_ROLES', userRoles)

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (state.token) {
        var decodedToken = jwt_decode(state.token)
        commit('SET_USER_CONTEXT', decodedToken)

        var userRoles = []
        for (var i = 0; i < decodedToken.roles.length; i++) {
          var roleName = decodedToken.roles[i].RoleName
          userRoles.push(roleName)
        }
        commit('SET_USER_ROLES', userRoles)
      }
      resolve()
    }).catch(error => {
      reject(error)
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_USER_CONTEXT', {})
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_USER_CONTEXT', {})
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
